package me.feng.servlet

import org.apache.catalina.websocket.WebSocketServlet
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletRequest
import org.apache.catalina.websocket.StreamInbound
import org.apache.catalina.websocket.MessageInbound
import java.nio.ByteBuffer
import java.nio.CharBuffer
import javax.servlet.annotation.WebServlet
import me.feng.util.Base64
import java.io.File
import java.io.FileOutputStream

@WebServlet(Array("/file.ws"))
class FileServlet extends WebSocketServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
    super.doGet(req, resp)
  }

  override def createWebSocketInbound(subProtocol: String, request: HttpServletRequest): StreamInbound = {
    return new MessageInbound() {
      
      var file:String = _
      
      override def onBinaryMessage(buffer: ByteBuffer) = {
        // Log
        println("Binary Message Receive: " + buffer.remaining());
        val fout = new FileOutputStream("/home/feng/"+file)
        val fcout = fout.getChannel()
        fcout.write(buffer)
        
        // Nothing
      }

      override def onTextMessage(buffer: CharBuffer) = {
    	file = buffer.toString()
      }
    }
  }
}